package com.ruoyi.web.controller.aggregation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.aggregation.dto.PageDTO;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.aggregation.User;
import com.ruoyi.system.domain.aggregation.Account;
import com.ruoyi.system.domain.aggregation.Withdraw;
import com.ruoyi.system.service.aggregation.IAggUserService;
import com.ruoyi.system.service.aggregation.IAccountService;
import com.ruoyi.system.service.aggregation.IWithdrawService;

/**
 * 商家管理Controller
 * 
 * @author ruoyi
 * @date 2025-01-12
 */
@RestController
@RequestMapping("/agg/merchant")
public class MerchantController
{
    @Autowired
    private IAggUserService userService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IWithdrawService withdrawService;

    /**
     * 商家列表分页查询
     */
    @PostMapping("/page")
    public AjaxResult page(@RequestBody PageDTO pageDTO)
    {
        try
        {
            PageHelper.startPage(pageDTO.getPageIndex().intValue(), pageDTO.getPageSize().intValue());
            User query = new User();
            query.setType(3); // 商家类型
            List<User> list = userService.selectUserList(query);
            PageInfo<User> pageInfo = new PageInfo<>(list);
            return AjaxResult.success(pageInfo);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取商家详情
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(@RequestParam Long id)
    {
        try
        {
            User user = userService.selectUserById(id);
            if (user == null || user.getType() != 3)
            {
                return AjaxResult.error("商家不存在");
            }
            return AjaxResult.success(user);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 编辑商家信息
     */
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody User user)
    {
        try
        {
            // 验证是否为商家
            User existingUser = userService.selectUserById(user.getId());
            if (existingUser == null || existingUser.getType() != 3)
            {
                return AjaxResult.error("商家不存在");
            }
            
            user.setType(3); // 确保类型为商家
            userService.updateUser(user);
            return AjaxResult.success("修改成功");
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除商家（软删除）
     */
    @PostMapping("/delete")
    public AjaxResult delete(@RequestParam Long id)
    {
        try
        {
            User user = userService.selectUserById(id);
            if (user == null || user.getType() != 3)
            {
                return AjaxResult.error("商家不存在");
            }
            
            userService.deleteUserById(id);
            return AjaxResult.success("删除成功");
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取商家收益统计
     * 用于商家提现页面展示收益数据
     */
    @GetMapping("/incomeStats")
    public AjaxResult incomeStats(@RequestParam(required = false) Long merchantId)
    {
        try
        {
            Long targetMerchantId = merchantId;
            
            // 如果没传merchantId，从token获取当前登录用户
            if (targetMerchantId == null) {
                targetMerchantId = SecurityUtils.getUserId();
                if (targetMerchantId == null) {
                    return AjaxResult.error("用户未登录");
                }
            }
            
            // 验证是否为商家
            User merchant = userService.selectUserById(targetMerchantId);
            if (merchant == null || merchant.getType() != 3) {
                return AjaxResult.error("商家不存在或类型不匹配");
            }
            
            // 获取账户信息
            Account account = accountService.selectAccountByUserId(targetMerchantId);
            if (account == null) {
                return AjaxResult.error("账户不存在");
            }
            
            // 查询待审核的提现金额
            Withdraw withdrawQuery = new Withdraw();
            withdrawQuery.setUserId(targetMerchantId);
            withdrawQuery.setStatue(1); // 待审核状态
            List<Withdraw> pendingWithdraws = withdrawService.selectWithdrawList(withdrawQuery);
            
            Long pendingAmount = 0L;
            for (Withdraw withdraw : pendingWithdraws) {
                pendingAmount += withdraw.getAmount();
            }
            
            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("totalIncome", account.getTotalBalance() != null ? account.getTotalBalance() : 0L);  // 总收益（分）
            result.put("availableAmount", account.getBalance() != null ? account.getBalance() : 0L);       // 可提现金额（分）
            result.put("pendingAmount", pendingAmount);                                                     // 待审核提现金额（分）
            
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("获取收益统计失败：" + e.getMessage());
        }
    }
}
